/**
 * @file 标记动画(演示如何沿线移动要素)
 */
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import Point from 'ol/geom/Point';
import Polyline from 'ol/format/Polyline';
import VectorSource from 'ol/source/Vector';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ';
import {
  Circle as CircleStyle,
  Fill,
  Icon,
  Stroke,
  Style,
} from 'ol/style';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {getVectorContext} from 'ol/render';
import resData from './route.json'

const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'
const attributions =
  '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
  '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';

const center = [-5639523.95, -3501274.52];
const map = new Map({
  target: document.getElementById('map'),
  view: new View({
    center: center,
    zoom: 10,
    minZoom: 2,
    maxZoom: 19,
  }),
  layers: [
    new TileLayer({
      source: new XYZ({
        attributions: attributions,
        url: 'https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=' + key,
        tileSize: 512,
        crossOrigin: 'Anonymous'
      }),
    }),
  ],
});

// 折线图形
const polyline = resData.routes[0].geometry

// 实例化折线格式实例对象
const route = new Polyline({
  factor: 1e6,
}).readGeometry(polyline, {
  dataProjection: 'EPSG:4326',
  featureProjection: 'EPSG:3857',
});

// 创建一个线段要素
const routeFeature = new Feature({
  type: 'route',
  geometry: route,
});
// 创建一个开始点要素
const startMarker = new Feature({
  type: 'icon',
  geometry: new Point(route.getFirstCoordinate()),
});
// 创建一个结束点要素
const endMarker = new Feature({
  type: 'icon',
  geometry: new Point(route.getLastCoordinate()),
});
// 克隆一个开始点要素
const position = startMarker.getGeometry().clone();
// 定义一个运动的要素
const geoMarker = new Feature({
  type: 'geoMarker',
  geometry: position,
});
// 定义一个样式对象
const styles = {
  'route': new Style({
    stroke: new Stroke({
      width: 6,
      color: [237, 212, 0, 0.8],
    }),
  }),
  'icon': new Style({
    image: new Icon({
      anchor: [0.5, 1],
      src: '/data/icon.png',
    }),
  }),
  'geoMarker': new Style({
    image: new CircleStyle({
      radius: 7,
      fill: new Fill({color: 'black'}),
      stroke: new Stroke({
        color: 'white',
        width: 2,
      }),
    }),
  }),
};
// 实例化一个矢量图层
const vectorLayer = new VectorLayer({
  source: new VectorSource({
    features: [routeFeature, geoMarker, startMarker, endMarker],
  }),
  style: function (feature) {
    return styles[feature.get('type')];
  },
});

map.addLayer(vectorLayer);


const speedInput = document.getElementById('speed');
const startButton = document.getElementById('start-animation');
let animating = false;
let distance = 0;
let lastTime;

function moveFeature(event) {
  const speed = Number(speedInput.value);
  // 最近一次图层渲染完后的时间
  const time = event.frameState.time;
  // 已经过去的时间
  const elapsedTime = time - lastTime;
  // 计算已经运动的轨迹距离，为啥对2取模呢? 每次移动的距离不能大于2
  distance = (distance + (speed * elapsedTime) / 1e6) % 2;
  lastTime = time;
  // 获取距离起点指定距离的经纬度
  const currentCoordinate = route.getCoordinateAt(
    distance > 1 ? 2 - distance : distance
  );
  // 更新运动的小点点的坐标
  position.setCoordinates(currentCoordinate);
  // 获取可以绘制图层的上下文;类似于canvas.getContext()
  const vectorContext = getVectorContext(event);
  // 给图层添加type是geoMarker的样式
  vectorContext.setStyle(styles.geoMarker);
  // 画一个移动的小点点的图形
  vectorContext.drawGeometry(position);
  // tell OpenLayers to continue the postrender animation
  // 让地图实例绘制
  map.render();
}
function startAnimation() {
  animating = true;
  lastTime = Date.now();
  startButton.textContent = 'Stop Animation';
  vectorLayer.on('postrender', moveFeature);
  // hide geoMarker and trigger map render through change event
  geoMarker.setGeometry(null);
}

function stopAnimation() {
  animating = false;
  startButton.textContent = 'Start Animation';

  // Keep marker at current animation position
  geoMarker.setGeometry(position);
  vectorLayer.un('postrender', moveFeature);
}

startButton.addEventListener('click', function () {
  if (animating) {
    stopAnimation();
  } else {
    startAnimation();
  }
});



